#include "CheckProcess.h"


const int CheckProcess::ProcessActive;
const int CheckProcess::ProcessInactive;


CheckProcess::CheckProcess(int refreshRate, QObject *parent) : QThread(parent){
    this -> processList = new  QList<Process *>();
    this -> refreshRate = refreshRate;
}


CheckProcess::~CheckProcess(){
    stop();
    deleteProcessList(this -> processList);
}


void CheckProcess::stop(){
    this -> quit();
    if (!this -> wait(100)){
        this -> terminate();
    }
}


void CheckProcess::deleteProcessList(QList<Process *> * processList){
    while (processList->isEmpty()){
        delete processList->first();
        processList -> pop_front();
    }
    delete processList;
}

void CheckProcess::setRefreshRate(int ms){
    this -> refreshRate = ms;
}

void CheckProcess::run(){
    qDebug() << "Analysing process...[" + QString::number(this->refreshRate) + "]";
    while (true){
        HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);
        if (hSnapshot == INVALID_HANDLE_VALUE){
            qDebug() << "Error while creating the toolhelp32snapshot";
            break;
        }
        QList<Process *> * processList = new QList<Process *>();
        PROCESSENTRY32 lppe;
        lppe.dwSize = sizeof(PROCESSENTRY32);
        bool result = Process32First(hSnapshot, &lppe);
        while (result){
            processList -> append(new Process(&lppe));
            result = Process32Next(hSnapshot, &lppe);
        }

        treatProcessList(processList);
        this -> deleteProcessList(processList);      //delete the temp list
        CloseHandle(hSnapshot);

        this -> msleep(this -> refreshRate);
    }
}


bool CheckProcess::processExist(QList<Process *> * processList, Process * process){
    for (int i = 0; i < processList -> size(); i++)
        if (processList -> at(i)-> getId() == process -> getId())
            return true;
    return false;
}




void CheckProcess::treatProcessList(QList<Process *> * processList){
    for (int i = 0; i < processList -> size(); i++){
        Process * p = processList -> at(i);
        if (!processExist(this -> processList, p)){              //The process has just started
            emit signalProcessStarted(p);
            Process * newProcess = new Process(p);               //Copy the new process into memory
            this -> processList -> append(newProcess);                              //Adding the new process into the processList
        }
    }

    for (int i = 0; i < this -> processList -> size(); i++){
        Process * p = this -> processList -> at(i);
        if (!processExist(processList, p)){              //The process has just stopped
            emit signalProcessStopped(p);
            this -> processList-> removeAt(i);                                      //Delete the process from the current list
        }
    }
}



